<!--
 * @Descripttion: 销售退货
 * @version:
 * @Author: cxguo
 * @Date: 2019-08-17 20:26:23
 * @LastEditors: cxguo
 * @LastEditTime: 2019-10-16 11:27:21
 -->
<template>
  <div>
    <el-main>
      <el-card shadow="never">
        <div slot="header" class="clearfix">
          <span>单号: {{ dataObj.saleNumber }}</span>
        </div>
        <el-form
          ref="saleForm"
          :inline="true"
          :model="dataObj"
          :rules="rules"
          label-position="left"
          label-width="100px"
          size="mini"
        >
          <el-form-item label="客户:" prop="customerId">
            <el-select v-model="dataObj.customerId" :filter-method="getCustomers" filterable placeholder="请选择">
              <el-option
                v-for="item in optionsData.customer"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="应付金额:" prop="amountPayable">
            <el-input v-model.number="dataObj.amountPayable" disabled />
          </el-form-item>
          <el-form-item label="实付金额:" prop="amountPaid">
            <el-input v-model.number="dataObj.amountPaid" />
          </el-form-item>
          <el-form-item label="是否收款:">
            <el-switch
              v-model="dataObj.state"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#cccccc"
            />
          </el-form-item>
          <el-form-item label="退货日期:">
            <el-date-picker
              v-model="dataObj.returnDate"
              type="datetime"
            />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="dataObj.remarks" style="width:400px;" />
          </el-form-item>
        </el-form>
        <div style="text-align: center">
          <el-button type="primary" size="medium" :loading="btnLoading.save" @click="btnSave">保存并新增</el-button>
          <el-button type="success" size="medium" :loading="btnLoading.save" @click="btnSave">保 存</el-button>
        </div>
      </el-card>
      <div class="margin-t10">
        <div>
          <el-button type="primary" size="medium" @click="btnAddTableData">添 加</el-button>
          <el-button type="danger" size="medium" @click="btnDelTableData">删 除</el-button>
        </div>
        <el-table
          ref="productTable"
          v-loading="tableLoading.goodsSelect"
          :data="tableData.goodsSelect"
          style="width: 100%"
          border
          @selection-change="onSelectionChange"
        >
          <el-table-column type="selection" width="60" align="center" />
          <el-table-column label="商品编号" width="100" prop="code" align="left" />
          <el-table-column label="商品名称" :show-overflow-tooltip="true" width="200" prop="name" align="left" />
          <el-table-column label="型号" width="100" prop="model" align="left" />
          <el-table-column label="类别" width="100" prop="typeName" align="left" />
          <el-table-column label="单位" width="60" prop="unit" align="center" />
          <el-table-column label="单价" width="100" prop="price" align="right" />
          <el-table-column label="数量" width="100" align="center" fixed="left">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.num" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="总额" width="130" :show-overflow-tooltip="true" prop="total" align="right" fixed="left">
            <template slot-scope="scope">
              {{ $amount(scope.row.price).multiply(scope.row.num).format() }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-main>
  </div>
</template>

<script>
import { oftenuse } from '@/libs/mixins'
import GoodsList from '@/views/goods'
import { saveData, getSaleReturnNumber, getDataByBillId, listGoodsByBillId } from '@/api/sale-return'
import { comboList } from '@/api/customer'
import moment from 'moment'

export default {
  name: 'SaleReturn',
  mixins: [oftenuse],
  props: {
    salereturnId: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      optionsData: {},
      rules: {
        supplierId: [
          { required: true, message: '请选择供应商', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    totalAmount: function() {
      const tableData = this.getTableData('goodsSelect')
      let result = 0
      tableData.forEach(item => {
        result += item.purchasingPrice * item.num
      })
      return this._.round(result, 2)
    }
  },
  watch: {
    'totalAmount': {
      handler(val) {
        this.$set(this.dataObj, 'amountPayable', val)
        this.$set(this.dataObj, 'amountPaid', val)
      },
      immediate: true
    }
  },
  created() {
    this.initData()
    this.$bus.$on('on-goods-select-sure', (selectData) => {
      const data = this.formatGoodsData(selectData)
      this.getTableData('goodsSelect').push(...data)
    })
    this.$once('hook:beforeDestroy', () => {
      this.$bus.$off('on-goods-select-sure')
    })
  },
  methods: {
    btnAddTableData() {
      this.$layer.iframe.addSingle({
        title: '选择商品',
        area: ['1000px', '400px'],
        name: 'iframe-goods',
        content: {
          content: GoodsList,
          props: {
            oper: 'select'
          }
        }
      })
    },
    btnDelTableData() {
      const selectData = this.getTableSelectionData('goodsSelect')
      if (!selectData) return
      const ids = selectData.map(item => { return item.code })
      const tableData = this.getTableData('goodsSelect')
      for (let i = 0; i < tableData.length; i++) {
        const item = tableData[i]
        if (ids.indexOf(item.code) !== -1) {
          this.$delete(tableData, i)
          i--
        }
      }
    },
    btnSave() {
      this.handleValid('saleForm').then(() => {
        const params = {
          returnList: this.dataObj,
          returnListGoodsList: this.getTableData('goodsSelect')
        }
        this.setBtnLoading('save', true)
        this.saveSaleOrder(params).then(() => {
          this.setBtnLoading('save', false)
        }).catch(err => {
          console.log(err)
          this.setBtnLoading('save', false)
        })
      })
    },
    // api
    formatGoodsData(tableData) {
      tableData.forEach(item => {
        item.goodsId = item.id
        item.price = item.lastPurchasingPrice
        item.total = this._.round(item.lastPurchasingPrice * item.num, 2)
        delete item.id
      })
      return tableData
    },
    getCustomers(params) {
      comboList(params).then(res => {
        if (res.data.flag) {
          this.$set(this.optionsData, 'customer', res.data.data)
        }
      })
    },
    getOperation() {
      if (this.salereturnId) return 'update'
      return 'save'
    },
    initSaveData() {
      this.setTableData('goodsSelect', [])
      this.setSaleNumber()
      const date = moment().format('YYYY-MM-DD HH:mm:ss')
      this.$set(this.dataObj, 'returnDate', date)
    },
    initUpdateData() {
      const billId = this.salereturnId
      getDataByBillId(billId).then(res => {
        if (!res.data.flag) return this.$notify.error({ title: '获取退货单详情失败！' })
        const data = res.data.data
        this.dataObj = data
        this.$set(this.optionsData, 'supplier', [{ id: data.supplierId, name: data.supplierName }])
      })
      listGoodsByBillId(billId).then(res => {
        if (!res.data.flag) return this.$notify.error({ title: '获取退货单商品失败！' })
        this.setTableData('goodsSelect', res.data.data)
        this.pageInfo = res.data.pageInfo
      })
    },
    initData() {
      if (this.getOperation() === 'save') this.initSaveData()
      if (this.getOperation() === 'update') this.initUpdateData()
    },
    /**
     * 设置采购单号
     */
    setSaleNumber() {
      getSaleReturnNumber().then(res => {
        if (res.data.flag) {
          this.$set(this.dataObj, 'saleNumber', res.data.data)
        }
      })
    },
    /**
     * 保存采购订单
     */
    saveSaleOrder(params) {
      return new Promise((resolve, reject) => {
        saveData(params).then(res => {
          resolve(res)
          this.$message[res.data.flag ? 'success' : 'error'](res.data.message)
        }).catch(err => {
          reject(err)
        })
      })
    },
    // on
    onSelectionChange(selectData) {
      this.setTableSelectionData('goodsSelect', selectData)
    }
  }
}
</script>

<style scoped>
</style>
